package com.life.muyu.controller;

import com.life.muyu.dto.ResultDTO;
import com.life.muyu.exception.CustomizeErrorCode;
import com.life.muyu.exception.CustomizeExcetpion;
import com.life.muyu.model.News;
import com.life.muyu.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;

/**
 * @Author zyb
 * @Date 2020-03-31 3:30 PM
 **/
@Controller
public class NewsController{

    @Autowired
    private NewsService newsService;


    @GetMapping("/news")
    public String toNews(Model model){
        return "news";
    }

    @GetMapping("/managerNews")
    public String adminToManagerNews(){

        return "news/managernews";
    }

    @GetMapping("/addNews")
    public String addNews(){
        return "news/addnews";
    }

    @GetMapping("/updateNews/{id}")
    public String updateNews(@PathVariable("id") Integer id,Model model) throws Exception {
        model.addAttribute("news",newsService.getById(id));
        return "news/updateNews";
    }


    @ResponseBody
    @PostMapping("/getNews")
    public Object getAllNews(@RequestParam("pageNo")  Integer pageNo) throws Exception {
        return  ResultDTO.okof(newsService.getNewsWithCondi(pageNo));
    }

    @ResponseBody
    @PostMapping("/addNews")
    public Object addNews(@RequestParam("newsCover")MultipartFile newsCover,News news){
        try {
            newsService.addNews(newsCover,news);
        } catch (CustomizeExcetpion ex) {
            ex.printStackTrace();
            return ResultDTO.errorOf(ex);
        }catch (Exception e){
            e.printStackTrace();
            return ResultDTO.errorOf(CustomizeErrorCode.SYSTEM_ERROR);
        }
        return ResultDTO.okof(CustomizeErrorCode.SUCCESS);
    }

    @PostMapping("/deleteNews")
    @ResponseBody
    public Object deleteNews(@RequestBody int[] ids){
        try{
            newsService.removeByIds(Collections.singletonList(ids));
//            newsService.deleteNews(ids);
        }catch (Exception e){
            e.printStackTrace();
            return ResultDTO.errorOf(CustomizeErrorCode.SYSTEM_ERROR);
        }
        return ResultDTO.okof(CustomizeErrorCode.SUCCESS);
    }

    @PostMapping("/updateNews")
    @ResponseBody
    public Object updateNews(@RequestParam(name = "newsCover",required = false) MultipartFile newsCover,News news){
        try {
            newsService.updateNews(newsCover,news);
        } catch (CustomizeExcetpion ex) {
            ex.printStackTrace();
            return ResultDTO.errorOf(ex);
        }catch (Exception e){
            e.printStackTrace();
            return ResultDTO.errorOf(CustomizeErrorCode.SYSTEM_ERROR);
        }
        return ResultDTO.okof(CustomizeErrorCode.SUCCESS);
    }
}
